package com.uetoken.cn.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.EncodeUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.pcn.helper.GetAuthorizationInfoListener;
import com.pcn.helper.PCNHelper;
import com.uetoken.cn.MainActivity;
import com.uetoken.cn.R;
import com.uetoken.cn.base.BaseActivity;
import com.uetoken.cn.base.MyApplication;
import com.uetoken.cn.bean.LocationBean;
import com.uetoken.cn.bean.LoginBean;
import com.uetoken.cn.bean.SignBean;
import com.uetoken.cn.common.ApiHelper;
import com.uetoken.cn.common.Constant;
import com.uetoken.cn.manager.UEDataManager;
import com.uetoken.cn.network.OkHttpUtils;
import com.uetoken.cn.network.Params;
import com.uetoken.cn.network.WebResponse;
import com.uetoken.cn.utils.GetCurrentLocation;
import com.umeng.commonsdk.debug.E;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.utils.SocializeUtils;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class LoginActivity extends BaseActivity implements WebResponse {

    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.edt_activity_login_account)
    EditText mEdtAccount;
    @BindView(R.id.edt_activity_login_pw)
    EditText mEdtPw;
    @BindView(R.id.tv_activity_login)
    TextView mTvLogin;
    @BindView(R.id.tv_activity_login_forget_pw)
    TextView mTvAForgetPw;
    @BindView(R.id.tv_activity_login_not_account)
    TextView mTvNotAccount;
    /**
     * 请求登录接口的请求码
     */
    private static final int REQUEST_NETWORK_LOGIN = 10;
    /**
     * 请求签到接口的请求码
     */
    private static final int REQUEST_NETWORK_SIGN = 20;
    @BindView(R.id.qqLoginTv)
    TextView qqLoginTv;
    @BindView(R.id.wechatLoginTv)
    TextView wechatLoginTv;
    @BindView(R.id.pcnLoginTv)
    TextView pcnLoginTv;
    @BindView(R.id.youguLoginTv)
    TextView youguLoginTv;
    /**
     * 别的activity跳转过来的标识
     */
    private String flag = "";
    /**
     * 经度
     */
    private String longitude = "0";
    /**
     * 纬度
     */
    private String latitude = "0";

    public SHARE_MEDIA mPlatform;
    /**
     * 第三方账号登录类型：0=UE,1-QQ、2-微信、3-微博、4-Pcn、5-优谷 ,
     */
    private int opentype = 0;
    private String appName = "";
    private HashMap<String, Integer> mPlatformMap;
    private String account;
    private String password;
    private String uid = "";
    private boolean isAuthorization = false;
    private String uriHost;
    private String actionType;
//    private boolean isToPay = false;//是否要跳转至支付界面

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        BarUtils.setStatusBarColor(this, ContextCompat.getColor(this, android.R.color.white), true);
        BarUtils.setStatusBarLightMode(this, true);
        mTvTitle.setText(getString(R.string.tv_login));
        EventBus.getDefault().register(this);
//        MyApplication.getInstance().setHandler(mHandler);
//        UMShareConfig config = new UMShareConfig();
//        config.isNeedAuthOnGetUserInfo(true);
//        UMShareAPI.get(LoginActivity.this).setShareConfig(config);
    }

    @Override
    public void initData() {
        mPlatformMap = UEDataManager.getInstance().getOpensType();
        Intent intent = getIntent();
        flag = intent.getStringExtra("flag");
        isAuthorization = intent.getBooleanExtra("isAuthorization", false);
        uriHost = getIntent().getStringExtra("uriHost");
        actionType = getIntent().getStringExtra("actionType");
        if ("login".equals(flag)) {
            uid = intent.getStringExtra("nodeCode");
            account = uid;
            appName = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).getString(Constant.SP_TRIRDPARTY_APP_NAME, "");
            toThirdpartyLogin();
        } else if ("authorization".equals(flag)) {
            uid = intent.getStringExtra("nodeCode");
        }

        AndPermission.with(this).runtime().permission(Permission.Group.LOCATION).onGranted(new Action<List<String>>() {
            @Override
            public void onAction(List<String> data) {
                //开始定位(用于签到)
                GetCurrentLocation.getLocationCity();
            }
        }).onDenied(new Action<List<String>>() {
            @Override
            public void onAction(List<String> data) {
                ToastUtils.showShort(getResources().getString(R.string.str_permission_refuse_causing_an_exception));
            }
        }).start();
    }

    @Override
    public void init() {

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        flag = intent.getStringExtra("flag");
        if ("login".equals(flag)) {
            dissmissDialog();
            uid = intent.getStringExtra("nodeCode");
            account = uid;
            toThirdpartyLogin();
        } else if ("authorization".equals(flag)) {
            uid = intent.getStringExtra("nodeCode");
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        dissmissDialog();
    }

    private void toThirdpartyLogin() {
        if (TextUtils.isEmpty(uid)) {
            ToastUtils.showShort(R.string.str_authorization_failed);
        } else {
            Login();
        }
    }

    @OnClick({R.id.tv_activity_login, R.id.tv_activity_login_forget_pw, R.id.tv_activity_login_not_account, R.id.qqLoginTv, R.id.wechatLoginTv, R.id.pcnLoginTv, R.id.youguLoginTv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_activity_login:
                appName = "UE";
                SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_TRIRDPARTY_APP_NAME, appName);
                account = mEdtAccount.getText().toString();
                password = mEdtPw.getText().toString();
                Login();
                break;
            case R.id.tv_activity_login_forget_pw:
                //忘记密码
                Intent intent = new Intent(this, ForgetPasswordActivity.class);
                intent.putExtra("pwd", "login");
                intent.putExtra("modify", "forget");
                startActivity(intent);
                break;
            case R.id.tv_activity_login_not_account:
                toRegisterActivity();
                break;
            case R.id.qqLoginTv:
                appName = "QQ";
                SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_TRIRDPARTY_APP_NAME, appName);
                UMShareAPI.get(LoginActivity.this).getPlatformInfo(LoginActivity.this, SHARE_MEDIA.QQ, authListener);
                break;
            case R.id.wechatLoginTv:
                appName = "WEIXIN";
                SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_TRIRDPARTY_APP_NAME, appName);
                UMShareAPI.get(LoginActivity.this).getPlatformInfo(LoginActivity.this, SHARE_MEDIA.WEIXIN, authListener);
                break;
            case R.id.pcnLoginTv:
                appName = "PCN";
                SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_TRIRDPARTY_APP_NAME, appName);
                showLoading();
//                toThirdpartyAPP("com.scce.pcn", "pcn://ue?actionType=5000");
                if (AppUtils.isAppInstalled("com.scce.pcn")) {
                    PCNHelper.toAuthorization(LoginActivity.this, null, "tNdWItFPQeudTDslFXfU", "ue");
                    finish();
                } else {
                    dissmissDialog();
                }
                break;
            case R.id.youguLoginTv:
                appName = "YOUGU";
                SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_TRIRDPARTY_APP_NAME, appName);
                toThirdpartyAPP("cn.com.yg", "yougu://ue?actionType=4000");
                break;
        }

    }

    /**
     * 启动Pcn、优谷，授权获取nodeCode
     */
    private void toThirdpartyAPP(String packageName, String uri) {
        if (AppUtils.isAppInstalled(packageName)) {
            //安装了优谷程序,则跳转到优谷app进行授权
            Intent intentToAPP = new Intent();
            intentToAPP.setData(Uri.parse(uri));
            startActivity(intentToAPP);
            finish();
        } else {
            dissmissDialog();
            ToastUtils.showShort(getResources().getString(R.string.str_do_not_install)
                    + ("YOUGU".equals(appName) ? getResources().getString(R.string.str_yg) : appName));
        }
    }

    UMAuthListener authListener = new UMAuthListener() {
        /**
         * @desc 授权开始的回调
         * @param platform 平台名称
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
            showLoading();
        }

        /**
         * @desc 授权成功的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param data 用户资料返回
         */
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            //成功了
            dissmissDialog();
            StringBuilder sb = new StringBuilder();
            if (action != 1) {
                for (String key : data.keySet()) {
                    sb.append(key).append(" : ").append(data.get(key)).append("\n");
                }
                uid = data.get("uid");
                account = uid;
                Login();
            }
            LogUtils.dTag("login==", "action = " + action + " sb = " + sb.toString());
        }

        /**
         * @desc 授权失败的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            //失败
            dissmissDialog();
            ToastUtils.showShort(t.getMessage());
        }

        /**
         * @desc 授权取消的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         */
        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            //取消了
            dissmissDialog();
            ToastUtils.showShort(R.string.str_user_cancelled);
        }
    };

    /**
     * 登录
     */
    private void Login() {
        opentype = mPlatformMap.get(appName);
        if (TextUtils.isEmpty(account)) {
            ToastUtils.showShort(getString(R.string.toast_account_can_not_empty));
            return;
        }
        if (opentype == mPlatformMap.get("UE")) {
            if (TextUtils.isEmpty(password)) {
                ToastUtils.showShort(getString(R.string.toast_password_can_not_empty));
                return;
            } else {
                password = EncodeUtils.base64Encode2String(password.getBytes());
            }
        } else {
            password = "";
        }
        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getLoginUrl(), REQUEST_NETWORK_LOGIN,
                Params.getLoginParams(account, password, opentype + ""));
    }

    @Override
    public void onSuccessResponse(Call call, String response, int requestCode) throws IOException {
        LogUtils.dTag("onSuccessResponse==", "onSuccessResponse== requestCode = " + requestCode + " response = " + response);
        switch (requestCode) {
            case REQUEST_NETWORK_LOGIN:
                dissmissDialog();
                LoginBean loginBean = new Gson().fromJson(response, LoginBean.class);
                if (loginBean.getResult() > 0) {
                    //保存用户nodeId
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_NODE_ID, String.valueOf(loginBean.getData().getNodeid()));
                    //保存用户nodeCode
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_NODE_CODE, loginBean.getData().getNodecode());
                    //保存用户nodeName
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_NODE_NAME, loginBean.getData().getNodename());
                    //保存用户手机号
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_MOBILE_NO, loginBean.getData().getMobileno());
                    //保存用户头像地址
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_HEAD_PHOTO, loginBean.getData().getPic());
                    //保存值为true，代表用户已登录
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_WHETHER_LOGIN, true);
                    //保存是否有支付密码的状态
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.IS_PAY_PWD, loginBean.getData().isIspaypwdnull());
                    //保存最大免密支付金额
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_MAXIMUM_SECRET_AMOUNT, String.valueOf(loginBean.getData().getMaxnotpwd()));
                    //保存未读消息数量
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_NEWMAIL_NUM, String.valueOf(loginBean.getData().getNewmailnum()));
                    //保存开通支付密码类型
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_NOT_PWD_PAY_TYPE, String.valueOf(loginBean.getData().getNotpwdpaytype()));

                    beginSign();
                    String payData = "";
                    try {
                        payData = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_OTHER_INFO).getString(Constant.THRID_APP_JSON_DATA, "");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    String authorizationData = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_OTHER_INFO).getString(Constant.SP_TRIRDPARTY_APP_REQUEST_AUTHORIZATION, "");
                    LogUtils.dTag("authorizationData==", "authorizationData== " + authorizationData);
                    if (!TextUtils.isEmpty(authorizationData)) {
//                        Uri uri = Uri.parse(authorizationData);
//                        uriHost = uri.getHost();
//                        actionType = uri.getQueryParameter("actionType");
//                        uid = uri.getQueryParameter("nodeCode");
//                        Intent intentToAuth = new Intent(LoginActivity.this, APPAuthorizationActivity.class);
//                        intentToAuth.putExtra("uriHost", uriHost);
//                        intentToAuth.putExtra("actionType", actionType);
//                        intentToAuth.putExtra("nodeCode", uid);
//                        startActivity(intentToAuth);
                        finish();
                    } else {
                        if (!TextUtils.isEmpty(payData)) {
                            //刷新下主界面
                            Intent successIntent = new Intent();
                            successIntent.setAction("paySuccess");
                            sendBroadcast(successIntent);

                            //从向商家支付界面跳转过来的,登录完成后直接跳到支付界面
                            startActivity(new Intent(this, PayToMerchantsActivity.class));
                            finish();
                        } else {
                            ActivityUtils.finishActivity(MainActivity.class);
                            startActivity(new Intent(this, MainActivity.class));
                            finish();
                        }
                    }
                    ToastUtils.showShort(loginBean.getMessage());
                } else {
                    if (opentype == mPlatformMap.get("UE")) {
                        ToastUtils.showShort(loginBean.getMessage());
                    } else {
                        toRegisterActivity();
                    }
                }
                break;
            case REQUEST_NETWORK_SIGN:
                //签到接口返回的result=-1时，为冻结状态
                SignBean signBean = new Gson().fromJson(response, SignBean.class);
                if (signBean.getResult() <= 0) {
                    ToastUtils.showShort(signBean.getMessage());
                    if (signBean.getResult() == -1) {
                        SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_WHETHER_LOGIN, false);
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onFailResponse(Call call, IOException e, int requestCode) {
        dissmissDialog();
        ToastUtils.showShort(e.getMessage());
    }

    /**
     * 开始签到
     */
    private void beginSign() {
        OkHttpUtils.getInstance().getStringWithParam(LoginActivity.this, ApiHelper.getUserSignUrl(), REQUEST_NETWORK_SIGN,
                Params.getUserSignParams(longitude, latitude));
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1000:
                    account = (String) msg.obj;
                    uid = account;
                    if (TextUtils.isEmpty(account)) {
                        ToastUtils.showShort(R.string.str_authorization_failed);
                    } else {
                        Login();
                    }
                    break;
            }
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        boolean isAuthQQ = UMShareAPI.get(LoginActivity.this).isAuthorize(LoginActivity.this, SHARE_MEDIA.QQ);
        if (isAuthQQ) {
            UMShareAPI.get(LoginActivity.this).deleteOauth(LoginActivity.this, SHARE_MEDIA.QQ, authListener);
        }
        boolean isAuthWEIXIN = UMShareAPI.get(LoginActivity.this).isAuthorize(LoginActivity.this, SHARE_MEDIA.WEIXIN);
        if (isAuthWEIXIN) {
            UMShareAPI.get(LoginActivity.this).deleteOauth(LoginActivity.this, SHARE_MEDIA.WEIXIN, authListener);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        GetCurrentLocation.destory();
        UMShareAPI.get(this).release();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 跳转注册界面
     */
    private void toRegisterActivity() {
        Intent intent = new Intent(this, RegisterActivity.class);
        intent.putExtra("opentype", opentype);
        intent.putExtra("longitude", longitude);
        intent.putExtra("latitude", latitude);
        intent.putExtra("uid", uid);
        startActivity(intent);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        UMShareAPI.get(this).onSaveInstanceState(outState);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getLocation(LocationBean locatinEvent) {
        //定位成功获取经纬度
        longitude = locatinEvent.getLogitude();
        latitude = locatinEvent.getLatitude();
    }

//    @Override
//    public void success(String s, String s1, String s2) {
//        appName = "PCN";
//        account = s2;
//        Login();
//    }
//
//    @Override
//    public void fail(int i, String s) {
//        ToastUtils.showShort(R.string.str_authorization_failed);
//    }
}
